package com.example.bookappgraduation.adapters;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide; // 引入Glide
import com.example.bookappgraduation.models.Book;
import com.example.bookappgraduation.BookDetailActivity;
import com.example.bookappgraduation.R;

import java.util.List;

public class BookAdapter extends RecyclerView.Adapter<BookAdapter.BookViewHolder> {

    private List<Book> bookList;
    private Context context;

    public BookAdapter(Context context, List<Book> bookList) {
        this.context = context;
        this.bookList = bookList;
    }

    @NonNull
    @Override
    public BookViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_book, parent, false);
        return new BookViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull BookViewHolder holder, int position) {
        Book book = bookList.get(position);//获取Book对象
        holder.textViewBookTitle.setText(book.getTitle());
        holder.textViewBookAuthor.setText(book.getSub1()); // 将Book对象的sub1设置到TextView

        holder.textViewBookSub.setText(book.getSub2());   // 将Book对象的sub2设置到TextView
        // 使用 Glide 加载图片
        Glide.with(context)
                .load(book.getImg())
                .placeholder(R.mipmap.ic_launcher) // 在图片加载完成前的占位图
                .error(R.drawable.ic_broken_image) // 加载错误图
                .into(holder.imageViewBookCover);

        holder.itemView.setOnClickListener(v -> {
            Intent intent = new Intent(context, BookDetailActivity.class);
            intent.putExtra("book_object", book); // 传递整个 Book 对象
            context.startActivity(intent);
        });
    }

    @Override
    public int getItemCount() {
        return bookList.size();
    }

    // 更新数据的方法
    public void updateData(List<Book> newBookList) {
        this.bookList.clear();//清空当前数据
        this.bookList.addAll(newBookList);
        notifyDataSetChanged();
    }


    static class BookViewHolder extends RecyclerView.ViewHolder {
        ImageView imageViewBookCover;
        TextView textViewBookTitle, textViewBookAuthor, textViewBookSub;

        public BookViewHolder(@NonNull View itemView) {
            super(itemView);//item_book组件的初始化
            imageViewBookCover = itemView.findViewById(R.id.imageViewBookCover);
            textViewBookTitle = itemView.findViewById(R.id.textViewBookTitle);
            textViewBookAuthor = itemView.findViewById(R.id.textViewBookAuthor);
            textViewBookSub = itemView.findViewById(R.id.textViewBookSub);
        }
    }
}